package com.bskj.kuaifu.nettyService.service.MQLister;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.enums.RailTypeEnum;
import com.bskj.kuaifu.bean.vo.UpRailMessage;
import com.bskj.kuaifu.nettyService.protobuf.Utils;
import com.bskj.kuaifu.nettyService.protobuf.generate.server2cli.rail.Rail;
import com.bskj.kuaifu.nettyService.service.utils.ClientConnection;
import com.bskj.kuaifu.nettyService.service.utils.ClientConnectionMap;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import io.netty.buffer.ByteBuf;

public class UpRailMsgLister extends DefaultConsumer {
	public UpRailMsgLister(Channel channel) {
		super(channel);
	}

	public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
			throws IOException {
		String message = new String(body, "UTF-8");
		UpRailMessage upRailMessage = JSONObject.parseObject(message, UpRailMessage.class);
		boolean deleteFlag = false;
		try {
			Map<String, Object> resultMap = sendUpRailMsg(upRailMessage.getParkLotId(), upRailMessage.getBoxNo(),
					RailTypeEnum.get(upRailMessage.getType()), upRailMessage.getRailNo());
			deleteFlag = (boolean)resultMap.get("result");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(deleteFlag) {
			getChannel().basicAck(envelope.getDeliveryTag(), false);
		} else {
			getChannel().basicNack(envelope.getDeliveryTag(), false, true);
		}
	}

	public Map<String, Object> sendUpRailMsg(Integer parkLotId, String boxNo, RailTypeEnum type, String railNo)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("result", false);
		ClientConnection clientConnection = ClientConnectionMap.getClientConnection(parkLotId + "_" + boxNo);
		if (clientConnection != null) {
			Rail.UpRail.Builder railBd = Rail.UpRail.newBuilder();
			railBd.setMark(type.getKey());
			railBd.setRailNo(railNo);
			ByteBuf byteBuf = Utils.pack2Client(railBd.build());
			clientConnection.getCtx().writeAndFlush(byteBuf);
			resultMap.put("result", true);
		}
		return resultMap;
	}
}
